"""
数据库连接管理模块
提供SQLite数据库连接和基础操作功能
"""

import os
import logging
from sqlalchemy import create_engine, event
from sqlalchemy.engine import Engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from typing import Optional

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 数据库基础类
Base = declarative_base()

class DatabaseManager:
    """数据库管理器"""
    
    def __init__(self, db_path: str = None):
        """
        初始化数据库管理器
        
        Args:
            db_path: 数据库文件路径，默认为项目根目录下的itts.db
        """
        if db_path is None:
            # 默认数据库路径为项目根目录下的itts.db
            project_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
            db_path = os.path.join(project_root, 'itts.db')
        
        self.db_path = db_path
        self.engine = None
        self.SessionLocal = None
        self._initialize_database()
    
    def _initialize_database(self):
        """初始化数据库连接"""
        try:
            # 创建数据库引擎
            self.engine = create_engine(
                f'sqlite:///{self.db_path}',
                echo=False,  # 设置为True可以看到SQL语句
                pool_pre_ping=True,  # 连接池预检查
                connect_args={
                    'check_same_thread': False,  # SQLite特有配置，允许多线程访问
                    'timeout': 20  # 连接超时时间
                }
            )
            
            # 启用SQLite外键约束
            @event.listens_for(self.engine, "connect")
            def set_sqlite_pragma(dbapi_connection, connection_record):
                cursor = dbapi_connection.cursor()
                cursor.execute("PRAGMA foreign_keys=ON")
                cursor.close()
            
            # 创建会话工厂
            self.SessionLocal = sessionmaker(
                autocommit=False,
                autoflush=False,
                bind=self.engine
            )
            
            logger.info(f"数据库连接初始化成功: {self.db_path}")
            
        except Exception as e:
            logger.error(f"数据库连接初始化失败: {e}")
            raise
    
    def create_tables(self):
        """创建所有数据表"""
        try:
            Base.metadata.create_all(bind=self.engine)
            logger.info("数据表创建成功")
        except Exception as e:
            logger.error(f"数据表创建失败: {e}")
            raise
    
    def get_session(self) -> Session:
        """
        获取数据库会话
        
        Returns:
            Session: 数据库会话对象
        """
        if self.SessionLocal is None:
            raise RuntimeError("数据库未初始化")
        
        return self.SessionLocal()
    
    def close_connection(self):
        """关闭数据库连接"""
        if self.engine:
            self.engine.dispose()
            logger.info("数据库连接已关闭")
    
    def check_connection(self) -> bool:
        """
        检查数据库连接状态
        
        Returns:
            bool: 连接是否正常
        """
        try:
            from sqlalchemy import text
            session = self.get_session()
            session.execute(text("SELECT 1"))
            session.close()
            return True
        except Exception as e:
            logger.error(f"数据库连接检查失败: {e}")
            return False
    
    def get_database_info(self) -> dict:
        """
        获取数据库信息
        
        Returns:
            dict: 数据库信息
        """
        try:
            from sqlalchemy import text
            session = self.get_session()
            
            # 获取数据库文件大小
            db_size = os.path.getsize(self.db_path) if os.path.exists(self.db_path) else 0
            
            # 获取表信息
            tables = session.execute(text("SELECT name FROM sqlite_master WHERE type='table'")).fetchall()
            table_count = len(tables)
            
            session.close()
            
            return {
                'path': self.db_path,
                'size_bytes': db_size,
                'size_mb': round(db_size / (1024 * 1024), 2),
                'table_count': table_count,
                'tables': [table[0] for table in tables]
            }
        except Exception as e:
            logger.error(f"获取数据库信息失败: {e}")
            return {}

# 全局数据库管理器实例
db_manager = None

def get_database_manager(db_path: str = None) -> DatabaseManager:
    """
    获取数据库管理器实例
    
    Args:
        db_path: 数据库文件路径
        
    Returns:
        DatabaseManager: 数据库管理器实例
    """
    global db_manager
    if db_manager is None:
        db_manager = DatabaseManager(db_path)
    return db_manager

def get_db_session() -> Session:
    """
    获取数据库会话
    
    Returns:
        Session: 数据库会话对象
    """
    return get_database_manager().get_session()